package com.elm.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.elm.dao.DiscussDao;
import com.elm.model.Discuss;
import com.elm.model.PageBean;
import com.elm.util.JDBCUtil;

public class DiscussDaoImpl implements DiscussDao{

	@Override
	public List<Discuss> getAllDiscussBySid(int sellerid,PageBean p) {
		List<Discuss> discusses = new ArrayList<Discuss>();
		Connection con = JDBCUtil.getConnection();
		StringBuffer sql = new StringBuffer("select * from discuss where sellerid = ? limit ?,?");
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(1, sellerid);
			pst.setInt(2, p.getStart());
			pst.setInt(3, p.getPageSize());
			ResultSet rs = pst.executeQuery();
			while(rs.next()) {
				Discuss discuss = new Discuss();
				discuss.setDiscussid(rs.getInt("discussid"));
				discuss.setMessage(rs.getString("message"));
				discuss.setSellerid(rs.getInt("sellerid"));
				discuss.setUserid(rs.getInt("userid"));
				discusses.add(discuss);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block


			e.printStackTrace();
		}
		
		return discusses;
	}

	@Override
	public boolean addDiscuss(Discuss d) {
		boolean flag = false;
		Connection con = JDBCUtil.getConnection();
		StringBuffer sql = new StringBuffer("insert into discuss (message,sellerid,userid) values(?,?,?)");
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setString(1, d.getMessage());
			pst.setInt(2, d.getSellerid());
			pst.setInt(3, d.getUserid());
			int i = pst.executeUpdate();
			if(i>0){
				flag=true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block


			e.printStackTrace();
		}
		
		return flag;
	}

	@Override
	public int getDiscussCount(int sellerid) {
		int count=0;
		Connection   con  =  JDBCUtil.getConnection();
		StringBuffer  sql = new StringBuffer("select * from discuss where discuss.sellerid=?");
		
			PreparedStatement pst;
			try {
				pst = con.prepareStatement(sql.toString());
				pst.setInt(1, sellerid);
				ResultSet rs = pst.executeQuery();
				while(rs.next()){
					count++;
				}
				 JDBCUtil.closeJDBC(pst, con);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
		return count;
	}

}
